﻿namespace OA.Infrastructure.Impl;

internal class SystemSettingService : ISystemSettingService
{
    private readonly DbContext _context;

    public SystemSettingService(DbContext context)
    {
        _context = context;
    }

    public async Task<OperationalResult<SystemSettings.QueryModel>> GetAsync(CancellationToken cancellationToken)
    {
        var result = new OperationalResult<SystemSettings.QueryModel>();

        try
        {
            var systemSetting = await _context.Set<SystemSettings>()
                .AsNoTracking()
                .FirstOrDefaultAsync(cancellationToken);

            systemSetting ??= new SystemSettings { SendMessage = false, ShowConsole = false };

            result.Data = GetQueryModel(systemSetting);
        }
        catch (Exception error)
        {
            result.Status = OperationalResult.ERROR;

            result.Message = error.ToString();
        }

        return result;
    }

    public async Task<OperationalResult> UpdateAsync(SystemSettings.UpdateModel systemSetting, CancellationToken cancellationToken)
    {
        var result = new OperationalResult();

        try
        {
            var entity = await _context.Set<SystemSettings>()
                .AsNoTracking()
                .FirstOrDefaultAsync(cancellationToken);

            if (entity is null)
            {
                entity = new SystemSettings
                {
                    SendMessage = systemSetting.SendMessage,
                    ShowConsole = systemSetting.ShowConsole,
                    SystemAdminCanApprove = systemSetting.SystemAdminCanApprove,
                };
            }
            else
            {
                entity.SendMessage = systemSetting.SendMessage;
                entity.ShowConsole = systemSetting.ShowConsole;
                entity.SystemAdminCanApprove = systemSetting.SystemAdminCanApprove;
            }

            _context.Set<SystemSettings>().Update(entity);

            var affectedRows = await _context.SaveChangesAsync(cancellationToken);

            result.Status = affectedRows > 0 ? OperationalResult.SUCCESS : OperationalResult.FAILURE;

            result.Message = $"{affectedRows} rows affected.";
        }
        catch (Exception error)
        {
            result.Status = OperationalResult.ERROR;

            result.Message = error.ToString();
        }

        return result;
    }

    private static SystemSettings.QueryModel GetQueryModel(SystemSettings systemSetting)
    {
        return new SystemSettings.QueryModel
        {
            Id = systemSetting.Id,
            CreatedDate = systemSetting.CreatedDate,
            LastModifiedDate = systemSetting.LastModifiedDate,
            SendMessage = systemSetting.SendMessage,
            ShowConsole = systemSetting.ShowConsole,
            SystemAdminCanApprove = systemSetting.SystemAdminCanApprove,
        };
    }
}